package com.yingpai.fitness.dvp_2_0.main.util.encrypt;

import android.content.Context;
import android.util.Log;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


/**
 *
 */
public class RsaEncrypt {

    private RSAPublicKey publicKey;
    private Context context;
    private static RsaEncrypt rsaEncrypt;

    public RSAPublicKey getPublicKey() {
        return publicKey;
    }


    public RsaEncrypt(Context context, String publicKeyFilePath) throws Exception {
        this.context = context;
        String public_key = getTextForFile();
//        String public_key = getKeyFromFile(publicKeyFilePath);
        loadPublicKey(public_key);
    }

    public String getKeyFromFile(String filePath) throws Exception {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));

        String line = null;
        List<String> list = new ArrayList<String>();
        while ((line = bufferedReader.readLine()) != null) {
            list.add(line);
        }

        // remove the firt line and last line
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 1; i < list.size() - 1; i++) {
            stringBuilder.append(list.get(i)).append("\r");
        }

        String key = stringBuilder.toString();
        System.out.println("%%%%key" + key);
        return key;
    }


    public void loadPublicKey(String publicKeyStr) throws Exception {
        System.out.println("#########" + publicKeyStr);
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            this.publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公钥非法");
        } catch (IOException e) {
            throw new Exception("公钥数据内容读取错误");
        } catch (NullPointerException e) {
            throw new Exception("公钥数据为空");
        }
    }

    public String encryptWithBase64(String string) throws Exception {
        //  http://commons.apache.org/proper/commons-codec/ : org.apache.commons.codec.binary.Base64
        // sun.misc.BASE64Encoder
        byte[] binaryData = encrypt(getPublicKey(), string.getBytes());
        String base64String = new BASE64Encoder().encodeBuffer(binaryData) /* org.apache.commons.codec.binary.Base64.encodeBase64(binaryData) */;
        return base64String;
    }


    public byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
        if (publicKey == null) {
            throw new Exception("加密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");//, new BouncyCastleProvider());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(plainTextData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }


    /**
     * 获取资源文件夹下的文件
     *
     * @return
     */
    private String getTextForFile() {
        try {
            InputStream is = context.getAssets().open("rsa_public_key.pem");
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader bufferedReader = new BufferedReader(isr);
            String line = null;
            List<String> list = new ArrayList<String>();
            while ((line = bufferedReader.readLine()) != null) {
                list.add(line);
            }
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 1; i < list.size() - 1; i++) {
                stringBuilder.append(list.get(i)).append("\r");
            }
            String key = stringBuilder.toString();
            Log.i("key", key);
            return key;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取加密类单例
     *
     * @param context
     * @return
     */
    public static RsaEncrypt getInstance(Context context) {
        try {
            if (rsaEncrypt == null) {
                rsaEncrypt = new RsaEncrypt(context, "");
                return rsaEncrypt;
            } else {
                return rsaEncrypt;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return rsaEncrypt;
        }
    }
}
